<script>
  import * as echarts from "echarts";
  import { onMount, onDestroy } from "svelte";
  import { useChartData } from "../utils/useChartData.js";

  export let endpoint = "";
  export let title = "";
  export let unit = "";
  export let authToken = "";
  export let polling = 0;
  export let data = null;

  let container;
  let chart;

  // Use shared data fetching logic
  const { loading, error, fetchData, cleanup } = useChartData();

  function renderChart(payload) {
    if (!chart) return;

    const seriesPayload = payload.series?.[0] ?? {};
    const dataItem = seriesPayload.data?.[0] ?? seriesPayload.data ?? null;

    const value = payload.value ?? dataItem?.value ?? seriesPayload.value ?? 0;
    const name = dataItem?.name ?? seriesPayload.name ?? title;

    const option = {
      title: {
        text: payload.title ?? title,
        left: "center"
      },
      series: [
        {
          type: "gauge",
          min: payload.min ?? seriesPayload.min ?? 0,
          max: payload.max ?? seriesPayload.max ?? 100,
          progress: {
            show: true,
            width: 12
          },
          axisLine: {
            lineStyle: {
              width: 12
            }
          },
          detail: {
            valueAnimation: true,
            formatter: (val) => `${val}${unit || payload.unit || ""}`,
            fontSize: 16
          },
          data: [
            {
              value,
              name
            }
          ]
        }
      ]
    };

    chart.setOption(option, true);
  }

  onMount(() => {
    chart = echarts.init(container);

    // Render provided data immediately
    if (data) {
      renderChart(data);
      loading.set(false);
    }
    // Otherwise fetch from endpoint
    else if (endpoint) {
      fetchData(endpoint, authToken, polling, renderChart);
    }
  });

  onDestroy(() => {
    cleanup();
    chart?.dispose();
  });
</script>

<div class="chart" bind:this={container}></div>
{#if $loading}
  <p class="status">Loading data...</p>
{:else if $error}
  <p class="status error">{$error}</p>
{/if}

<style>
  .chart {
    width: 100%;
    min-height: 260px;
  }
  .status {
    margin-top: 0.5rem;
    font-size: 0.875rem;
    color: var(--muted-color, #555);
  }
  .status.error {
    color: #c0392b;
  }
</style>

